import { AStar } from "./AStar";
import { GridData } from "./GridData";
import { Node } from "./Node";
/*
 * 网格可视化
 * */
export class GridView extends Laya.Sprite {
    private cellSize: number;
    private gridData: GridData;
    private aStar: AStar;

    constructor(gridData: GridData) {
        super();
        this.cellSize = 10; //每个格子20宽高 像素
        this.gridData = gridData; //网格数据对象
        this.size(gridData.cols * this.cellSize, gridData.rows * this.cellSize); //设置视图的宽高，要不然获取不到点击事件

        this.aStar = new AStar(gridData);

        this.on(Laya.Event.CLICK, this, this.mouseHandler);
    }

    //屏幕点击回调事件（设置当前格子是否可行走）
    private mouseHandler(event: Laya.Event) {
        const x = Math.floor(event.stageX / this.cellSize);
        const y = Math.floor(event.stageY / this.cellSize);
        this.gridData.setWalkable(x, y, !this.gridData.getNode(x, y).walkable);
        //this.gridData.setWalkable(x, y, false);
        this.drawGrid();
    }

    //绘制网格
    private drawGrid() {
        this.graphics.clear();

        //遍历绘制
        //创建所有的节点
        for (let i = 0; i < this.gridData.cols; i++) {
            for (let j = 0; j < this.gridData.rows; j++) {
                this.graphics.drawRect(i * this.cellSize, j * this.cellSize, this.cellSize, this.cellSize, this.drawRect(i, j), "#ffffff", 1);
            }
        }

        this.findPath();
    }

    private drawRect(x: number, y: number) {
        const node = this.gridData.nodes[x][y];
        if (!node.walkable) return "#000000";
        if (node === this.gridData.startNode) return "#00ffff";
        if (node === this.gridData.endNode) return "#00ffff";
        return "#999999";
    }

    //从A星算法获取路径
    private findPath() {
        console.time("search");
        this.gridData.setNormalStatus();
        this.aStar.findPath();

        if (this.aStar.search()) {
            console.timeEnd("search");
            //绘制访问过的地方
            this.drawVisited(this.aStar.getVisited());
            //绘制路径
            this.showPath(this.aStar.getPath());
        } else {
            console.timeEnd("search");
        }
    }

    //显示计算出来的移动路径
    private showPath(arr: Node[]) {
        const radius = this.cellSize / 2;
        for (let node of arr) {
            this.graphics.drawCircle(node.x * this.cellSize + radius, node.y * this.cellSize + radius, (radius / 5) * 4, "#0000ff");
        }
    }

    //
    private drawVisited(arr: Node[]) {
        for (let node of arr) {
            this.graphics.drawRect(node.x * this.cellSize, node.y * this.cellSize, this.cellSize, this.cellSize, "#eeeeee", "#ffffff", 1);
        }
    }
}
